﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using RAP.Framework.Libary.DataSource.Model;
using RAP.Framework.Libary.Utils;

namespace RAP.Framework.Libary.DataSource.DataReader
{
  /// <summary>
  /// 数据解析基类
  /// </summary>
  public abstract class DataReaderParser : IDataReaderParser
  {
    /// <summary>
    /// 获取DataReader的字段信息
    /// </summary>
    /// <param name="reader">IDataReader对象</param>
    /// <param name="pickFields">读取第一条记录的指定列，如果该参数为空或空集合，则默认读取所有数据的全部列，该参数的具体解析规则可通过重载ParseData函数来自定义</param>
    /// <returns></returns>
    public virtual IList<DBField> GetFields(IDataReader reader, IList pickFields)
    {
      var fields = new List<DBField>();
      if (pickFields.IsNullOrEmpty() || pickFields.First<string>() == "*")
      {
        for (var i = 0; i < reader.FieldCount; i++)
        {
          fields.Add(new DBField
          {
            Name = reader.GetName(i),
            Type = reader.GetDataTypeName(i),
            Index = i
          });
        }
      }
      else
      {
        for (int i = 0; i < pickFields.Count; i++)
        {
          var field = pickFields[i].ToString().Trim();
          var index = reader.GetOrdinal(field);
          fields.Add(new DBField
          {
            Name = field,
            Type = reader.GetDataTypeName(index),
            Index = index
          });
        }
      }
      return fields;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="dataReader"></param>
    /// <param name="pickFields"></param>
    /// <param name="type"></param>
    /// <param name="parseContext">解析时用到的上下文对象</param>
    /// <returns></returns>
    public virtual ParseResult ParseData(IDataReader dataReader, IList pickFields, string type, DataParseContext parseContext)
    {
      throw new NotImplementedException();
    }

    /// <summary>
    /// 将数据库的值转换成C#类型
    /// </summary>
    /// <param name="dataReader"></param>
    /// <param name="field"></param>
    /// <returns></returns>
    public virtual object GetDBValue(IDataReader dataReader, DBField field)
    {
      object dbValue = dataReader.GetValue(field.Index);
      if (dbValue == null || dbValue == DBNull.Value)
      {
        dbValue = null;
      }
      if(field.ModelName.IsNotNullOrEmpty())
      {
        //将字段按指定实体模型名称转换类型

      }
      return dbValue;
    }

    /// <summary>
    /// 创建数据模型
    /// </summary>
    /// <param name="resultTypeName">模型类型名称</param>
    /// <param name="properites"></param>
    /// <returns></returns>
    public virtual object CreateDataModel(string resultTypeName = null, IDictionary properites = null)
    {
      var data = new ListDictionary();
      if (properites.IsNotNullOrEmpty())
      {
        properites.CopyTo(data);
      }
      return data;
    }
  }
}
